($ => {
  $.fn.advancedSearchWithCollapse = function (view, onSearch, options) {
    options ??= {};
    options = { view, onSearch, ...options };

    const $this = $(this[0]);
    const $title = $('<div />');
    const $collapseAction = $('<div />');
    const $advancedSearch = $('<div />');
    const $titleText = $('<span style="cursor: pointer;">高级搜索</span>');

    $title.append($collapseAction, $titleText);
    $this.append($title, $advancedSearch);

    $this.css({
      display: 'flex',
      flexWrap: 'nowrap',
      flexDirection: 'column',
      padding: '5px',
      borderBottom: '1px solid #eee',
    });

    $title.css({
      display: 'flex',
      alignItems: 'center',
      height: '26px',
      userSelect: 'none',
    });

    $collapseAction.css({
      marginRight: '5px',
    });

    $advancedSearch.css({
      marginTop: '15px',
    });

    const expand = () => {
      $collapseAction.dxButton('instance').option('icon', 'chevronup');
      $advancedSearch.show();
    };

    const collapse = () => {
      $collapseAction.dxButton('instance').option('icon', 'chevrondown');
      $advancedSearch.hide();
    };

    const collapseOrExpand = () => {
      if ($collapseAction.dxButton('instance').option('icon') === 'chevrondown') {
        expand();
      } else {
        collapse();
      }
    };

    $collapseAction.dxButton({
      icon: 'chevrondown',
      stylingMode: 'text',
      focusStateEnabled: false,
      hoverStateEnabled: false,
      onClick: collapseOrExpand,
    });

    $titleText.on('click', collapseOrExpand);

    const advancedSearch = $advancedSearch.advancedSearch(view, onSearch, options);

    $advancedSearch.hide();

    return {
      expand,
      collapse,
      collapseOrExpand,
      ...advancedSearch,
    };
  };
})(jQuery);
